// src/utils/request.js
import axios from 'axios';
// 创建一个 Axios 实例
const service = axios.create({
  baseURL:'192.168.1.90:8080',
  timeout: 30000 // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  config => {
      // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    if (!isToken) {
        // 在请求头中添加 token 或其他信息
        let userinfo=JSON.parse(localStorage.getItem('user'));
        let token=null;
        if(userinfo && userinfo['token']){
          token = userinfo['token'];
        }
        if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
        }
    }
    config.baseURL = service.baseURL;
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use((res) => {
    if(res.data.code ==-1){
        console.log('响应拦截');
    }
    return res.data;
  }, (error) => {
    console.log('error', error);
    let { message } = error;
    if (message === "Network Error") {
      message = "服务器链接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 2000
    })
    return Promise.reject(error)
  
  });

export default service;